package cn.slipi.core.component.loadbalance;

import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.ServiceLoader;

/**
 * LoadBalanceFactory
 */
public class LoadBalanceFactory {

    private static final ServiceLoader<LoadBalanceSelector> SERVICE_LOADER =
            ServiceLoader.load(LoadBalanceSelector.class);

    public static LoadBalanceSelector of(final String algorithm) {
        List<LoadBalanceSelector> list = new ArrayList<>();
        for (LoadBalanceSelector loadBalanceSelector : SERVICE_LOADER) {
            list.add(loadBalanceSelector);
        }
        return list.stream()
                .filter(los -> StringUtils.equals(los.getAlgorithm(), algorithm))
                .findFirst()
                .orElse(new RandomLoadBalanceSelector());
    }
}
